package com.example.managemyself.util;

import android.content.Context;
import android.util.Log;

import com.example.managemyself.data.database.AppDatabase;
import com.example.managemyself.data.model.DiaryEntry;
import com.example.managemyself.data.model.Task;
import com.example.managemyself.data.model.User;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * AI贴身助手管理器
 * 为AI提供用户的完整上下文信息，包括日记、任务、习惯等
 */
public class AIPersonalAssistant {
    
    private static final String TAG = "AIPersonalAssistant";
    
    private static AIPersonalAssistant instance;
    private final AppDatabase database;
    private final UserManager userManager;
    private final ExecutorService executorService;
    private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日", Locale.getDefault());
    
    private AIPersonalAssistant(Context context) {
        database = AppDatabase.getInstance(context);
        userManager = UserManager.getInstance();
        executorService = Executors.newSingleThreadExecutor();
    }
    
    public static synchronized AIPersonalAssistant getInstance(Context context) {
        if (instance == null) {
            instance = new AIPersonalAssistant(context.getApplicationContext());
        }
        return instance;
    }
    
    /**
     * 为AI生成用户的完整上下文信息
     */
    public void generateUserContext(UserContextCallback callback) {
        executorService.execute(() -> {
            try {
                User currentUser = userManager.getCurrentUser();
                if (currentUser == null) {
                    callback.onResult("用户未登录，无法获取个人信息");
                    return;
                }
                
                StringBuilder context = new StringBuilder();
                
                // 基本用户信息
                context.append("=== 用户基本信息 ===\n");
                context.append("用户名：").append(currentUser.getDisplayName()).append("\n");
                context.append("注册时间：").append(formatDate(currentUser.getCreatedDate())).append("\n");
                context.append("用户类型：").append(currentUser.isAdmin() ? "管理员" : "普通用户").append("\n\n");
                
                // 获取最近的日记信息
                appendRecentDiaries(context, currentUser.getId());
                
                // 获取任务信息
                appendTasksInfo(context, currentUser.getId());
                
                // 获取用户行为模式
                appendUserPatterns(context, currentUser.getId());
                
                callback.onResult(context.toString());
                
            } catch (Exception e) {
                Log.e(TAG, "生成用户上下文失败", e);
                callback.onResult("获取用户信息时出现错误");
            }
        });
    }
    
    /**
     * 获取用户最近的活动摘要
     */
    public void getRecentActivitySummary(int days, ActivitySummaryCallback callback) {
        executorService.execute(() -> {
            try {
                User currentUser = userManager.getCurrentUser();
                if (currentUser == null) {
                    callback.onResult("用户未登录");
                    return;
                }
                
                Calendar calendar = Calendar.getInstance();
                calendar.add(Calendar.DAY_OF_YEAR, -days);
                Date startDate = calendar.getTime();
                
                StringBuilder summary = new StringBuilder();
                summary.append("=== 最近").append(days).append("天活动摘要 ===\n");
                
                // 获取最近的日记
                List<DiaryEntry> recentDiaries = database.diaryEntryDao().getDiariesAfterDateSync(startDate);
                if (!recentDiaries.isEmpty()) {
                    summary.append("\n📝 日记记录（").append(recentDiaries.size()).append("条）：\n");
                    for (DiaryEntry diary : recentDiaries) {
                        summary.append("• ").append(formatDate(diary.getDate())).append("：")
                               .append(diary.getTitle()).append("\n");
                        if (diary.getContent() != null && diary.getContent().length() > 50) {
                            summary.append("  内容摘要：").append(diary.getContent().substring(0, 50)).append("...\n");
                        }
                    }
                }
                
                // 获取最近的任务
                List<Task> recentTasks = database.taskDao().getTasksAfterDateSync(startDate);
                if (!recentTasks.isEmpty()) {
                    summary.append("\n✅ 任务情况（").append(recentTasks.size()).append("个）：\n");
                    int completedTasks = 0;
                    for (Task task : recentTasks) {
                        if (task.isCompleted()) completedTasks++;
                        summary.append("• ").append(task.getTitle())
                               .append(task.isCompleted() ? "（已完成）" : "（未完成）").append("\n");
                    }
                    summary.append("完成率：").append(String.format("%.1f%%", (completedTasks * 100.0 / recentTasks.size()))).append("\n");
                }
                
                callback.onResult(summary.toString());
                
            } catch (Exception e) {
                Log.e(TAG, "获取活动摘要失败", e);
                callback.onResult("获取活动摘要时出现错误");
            }
        });
    }
    
    /**
     * 搜索用户的历史记录
     */
    public void searchUserHistory(String keyword, HistorySearchCallback callback) {
        executorService.execute(() -> {
            try {
                User currentUser = userManager.getCurrentUser();
                if (currentUser == null) {
                    callback.onResult("用户未登录，无法搜索历史记录");
                    return;
                }
                
                StringBuilder result = new StringBuilder();
                result.append("=== 搜索结果：").append(keyword).append(" ===\n");
                
                // 搜索日记
                List<DiaryEntry> diaryResults = database.diaryEntryDao().searchDiariesSync("%" + keyword + "%");
                if (!diaryResults.isEmpty()) {
                    result.append("\n📝 相关日记（").append(diaryResults.size()).append("条）：\n");
                    for (DiaryEntry diary : diaryResults) {
                        result.append("• ").append(formatDate(diary.getDate())).append("：")
                              .append(diary.getTitle()).append("\n");
                        if (diary.getContent() != null && diary.getContent().contains(keyword)) {
                            // 提取包含关键词的片段
                            String[] sentences = diary.getContent().split("[。！？\\n]");
                            for (String sentence : sentences) {
                                if (sentence.contains(keyword)) {
                                    result.append("  \"").append(sentence.trim()).append("\"\n");
                                    break;
                                }
                            }
                        }
                    }
                }
                
                // 搜索任务
                List<Task> taskResults = database.taskDao().searchTasksSync("%" + keyword + "%");
                if (!taskResults.isEmpty()) {
                    result.append("\n✅ 相关任务（").append(taskResults.size()).append("个）：\n");
                    for (Task task : taskResults) {
                        result.append("• ").append(task.getTitle())
                              .append("（").append(task.getType()).append("）")
                              .append(task.isCompleted() ? " ✓" : " ○").append("\n");
                    }
                }
                
                if (diaryResults.isEmpty() && taskResults.isEmpty()) {
                    result.append("\n未找到包含\"").append(keyword).append("\"的相关记录。");
                }
                
                callback.onResult(result.toString());
                
            } catch (Exception e) {
                Log.e(TAG, "搜索历史记录失败", e);
                callback.onResult("搜索历史记录时出现错误");
            }
        });
    }
    
    /**
     * 为AI对话增强上下文
     */
    public void enhanceAIMessage(String userMessage, EnhancedMessageCallback callback) {
        // 检查用户消息是否包含个人信息查询
        String lowerMessage = userMessage.toLowerCase();
        
        if (containsPersonalQuery(lowerMessage)) {
            // 需要个人信息的查询
            if (lowerMessage.contains("日记") || lowerMessage.contains("写了什么") || lowerMessage.contains("记录")) {
                handleDiaryQuery(userMessage, callback);
            } else if (lowerMessage.contains("任务") || lowerMessage.contains("做了什么") || lowerMessage.contains("完成")) {
                handleTaskQuery(userMessage, callback);
            } else if (lowerMessage.contains("最近") || lowerMessage.contains("这几天")) {
                handleRecentActivityQuery(userMessage, callback);
            } else {
                // 通用个人信息查询
                generateUserContext(context -> {
                    String enhancedMessage = "用户问：" + userMessage + "\n\n" +
                                           "请基于以下用户信息回答：\n" + context + "\n\n" +
                                           "注意：你是用户的贴身AI助手，对用户的情况了如指掌，请用亲切、个性化的语调回答。";
                    callback.onResult(enhancedMessage);
                });
            }
        } else {
            // 普通对话，添加基本上下文
            User currentUser = userManager.getCurrentUser();
            if (currentUser != null) {
                String enhancedMessage = "用户" + currentUser.getDisplayName() + "说：" + userMessage + "\n\n" +
                                       "请作为用户的贴身AI助手，用亲切、个性化的语调回答。";
                callback.onResult(enhancedMessage);
            } else {
                callback.onResult(userMessage);
            }
        }
    }
    
    // 私有辅助方法
    private void appendRecentDiaries(StringBuilder context, int userId) {
        try {
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DAY_OF_YEAR, -7); // 最近7天
            Date weekAgo = calendar.getTime();
            
            List<DiaryEntry> recentDiaries = database.diaryEntryDao().getDiariesAfterDateSync(weekAgo);
            
            context.append("=== 最近7天日记记录 ===\n");
            if (recentDiaries.isEmpty()) {
                context.append("最近没有写日记\n\n");
            } else {
                for (DiaryEntry diary : recentDiaries) {
                    context.append(formatDate(diary.getDate())).append("：").append(diary.getTitle()).append("\n");
                    if (diary.getContent() != null && diary.getContent().length() > 100) {
                        context.append("内容摘要：").append(diary.getContent().substring(0, 100)).append("...\n");
                    }
                }
                context.append("\n");
            }
        } catch (Exception e) {
            Log.e(TAG, "获取最近日记失败", e);
        }
    }
    
    private void appendTasksInfo(StringBuilder context, int userId) {
        try {
            List<Task> allTasks = database.taskDao().getAllTasksSync();
            List<Task> pendingTasks = database.taskDao().getPendingTasksSync();
            
            context.append("=== 任务情况 ===\n");
            context.append("总任务数：").append(allTasks.size()).append("\n");
            context.append("待完成任务：").append(pendingTasks.size()).append("\n");
            
            if (!pendingTasks.isEmpty()) {
                context.append("近期待办：\n");
                for (int i = 0; i < Math.min(5, pendingTasks.size()); i++) {
                    Task task = pendingTasks.get(i);
                    context.append("• ").append(task.getTitle()).append("（").append(task.getType()).append("）\n");
                }
            }
            context.append("\n");
        } catch (Exception e) {
            Log.e(TAG, "获取任务信息失败", e);
        }
    }
    
    private void appendUserPatterns(StringBuilder context, int userId) {
        context.append("=== 用户行为模式 ===\n");
        context.append("我是你的贴身AI助手，对你的生活习惯、兴趣爱好、工作学习模式都很了解。\n");
        context.append("我会根据你的历史记录和行为模式，为你提供个性化的建议和帮助。\n\n");
    }
    
    private boolean containsPersonalQuery(String message) {
        String[] personalKeywords = {
            "我", "我的", "日记", "任务", "做了什么", "写了什么", "最近", "这几天", 
            "昨天", "前天", "上周", "完成", "记录", "活动", "情况"
        };
        
        for (String keyword : personalKeywords) {
            if (message.contains(keyword)) {
                return true;
            }
        }
        return false;
    }
    
    private void handleDiaryQuery(String userMessage, EnhancedMessageCallback callback) {
        // 提取日期相关关键词
        if (userMessage.contains("昨天")) {
            searchDiaryByDate(-1, userMessage, callback);
        } else if (userMessage.contains("前天")) {
            searchDiaryByDate(-2, userMessage, callback);
        } else if (userMessage.contains("最近") || userMessage.contains("这几天")) {
            getRecentActivitySummary(7, summary -> {
                String enhancedMessage = "用户问：" + userMessage + "\n\n" +
                                       "基于用户的最近活动：\n" + summary + "\n\n" +
                                       "请作为贴身助手，详细回答用户的问题。";
                callback.onResult(enhancedMessage);
            });
        } else {
            // 搜索包含特定关键词的日记
            String keyword = extractKeyword(userMessage);
            if (!keyword.isEmpty()) {
                searchUserHistory(keyword, result -> {
                    String enhancedMessage = "用户问：" + userMessage + "\n\n" +
                                           "搜索结果：\n" + result + "\n\n" +
                                           "请基于搜索结果回答用户的问题。";
                    callback.onResult(enhancedMessage);
                });
            } else {
                generateUserContext(context -> {
                    String enhancedMessage = "用户问：" + userMessage + "\n\n" +
                                           "用户信息：\n" + context + "\n\n" +
                                           "请作为贴身助手回答。";
                    callback.onResult(enhancedMessage);
                });
            }
        }
    }
    
    private void handleTaskQuery(String userMessage, EnhancedMessageCallback callback) {
        getRecentActivitySummary(7, summary -> {
            String enhancedMessage = "用户问：" + userMessage + "\n\n" +
                                   "用户最近的任务情况：\n" + summary + "\n\n" +
                                   "请作为贴身助手，基于任务完成情况回答用户的问题。";
            callback.onResult(enhancedMessage);
        });
    }
    
    private void handleRecentActivityQuery(String userMessage, EnhancedMessageCallback callback) {
        int days = extractDaysFromMessage(userMessage);
        getRecentActivitySummary(days, summary -> {
            String enhancedMessage = "用户问：" + userMessage + "\n\n" +
                                   "用户最近" + days + "天的活动：\n" + summary + "\n\n" +
                                   "请作为贴身助手，详细总结用户的近期情况。";
            callback.onResult(enhancedMessage);
        });
    }
    
    private void searchDiaryByDate(int daysAgo, String userMessage, EnhancedMessageCallback callback) {
        executorService.execute(() -> {
            try {
                Calendar calendar = Calendar.getInstance();
                calendar.add(Calendar.DAY_OF_YEAR, daysAgo);
                Date targetDate = calendar.getTime();
                
                List<DiaryEntry> diaries = database.diaryEntryDao().getDiariesByDateSync(targetDate);
                
                StringBuilder result = new StringBuilder();
                if (diaries.isEmpty()) {
                    result.append(formatDate(targetDate)).append("没有日记记录");
                } else {
                    result.append(formatDate(targetDate)).append("的日记：\n");
                    for (DiaryEntry diary : diaries) {
                        result.append("标题：").append(diary.getTitle()).append("\n");
                        result.append("内容：").append(diary.getContent()).append("\n");
                    }
                }
                
                String enhancedMessage = "用户问：" + userMessage + "\n\n" +
                                       "查询结果：\n" + result.toString() + "\n\n" +
                                       "请作为贴身助手，基于日记内容回答用户的问题。";
                callback.onResult(enhancedMessage);
                
            } catch (Exception e) {
                Log.e(TAG, "按日期搜索日记失败", e);
                callback.onResult(userMessage);
            }
        });
    }
    
    private String extractKeyword(String message) {
        // 简单的关键词提取逻辑
        String[] commonWords = {"我", "的", "了", "是", "在", "有", "和", "与", "或", "但", "然后", "因为", "所以"};
        String[] words = message.split("[\\s，。！？、]");
        
        for (String word : words) {
            if (word.length() > 1) {
                boolean isCommon = false;
                for (String common : commonWords) {
                    if (word.equals(common)) {
                        isCommon = true;
                        break;
                    }
                }
                if (!isCommon) {
                    return word;
                }
            }
        }
        return "";
    }
    
    private int extractDaysFromMessage(String message) {
        if (message.contains("最近")) {
            if (message.contains("一周") || message.contains("7天")) return 7;
            if (message.contains("三天")) return 3;
            if (message.contains("五天")) return 5;
            return 7; // 默认7天
        }
        return 3; // 默认3天
    }
    
    private String formatDate(Date date) {
        if (date == null) return "未知日期";
        return dateFormat.format(date);
    }
    
    // 回调接口
    public interface UserContextCallback {
        void onResult(String context);
    }
    
    public interface ActivitySummaryCallback {
        void onResult(String summary);
    }
    
    public interface HistorySearchCallback {
        void onResult(String result);
    }
    
    public interface EnhancedMessageCallback {
        void onResult(String enhancedMessage);
    }
} 